package com.srwl.mytx.adapter;

import android.content.Context;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.activity.BaseActivity;
import com.srwl.mytx.dao.DBManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Message;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.im.conversation.Conversation;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.DateUtils;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.MoonUtils;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.BottomBarBadge;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class ConversationListAdapter extends RecyclerView.Adapter<ConversationListAdapter.ViewHolder> {
    private static final String TAG = "ConversationListAdapter";
    public static final int REFRESH_MESSAGE = 0;
    public static final int REFRESH_USER_INFO = 1;
    public static final int REFRESH_BACKGROUND = 2;
    private Context context;
    private List<Conversation> conversationList;
    private List<Conversation> filterConversationList = new ArrayList<>();
    private InteractionListener listener;
    private List<String> idList = new ArrayList<>();//需要下载用户信息的id列表
    private boolean showFilterData;
    private ConversationFilter conversationFilter;
    private CharSequence filterKeyWord;

    public ConversationListAdapter(Context context, List<Conversation> conversationList) {
        this.context = context;
        this.conversationList = conversationList;
    }

    public ConversationListAdapter(Context context, List<Conversation> conversationList, InteractionListener mOnItemClickListener) {
        this.context = context;
        this.conversationList = conversationList;
        this.listener = mOnItemClickListener;
    }


    public void setOnItemClickListener(InteractionListener mOnItemClickListener) {
        this.listener = mOnItemClickListener;
    }


    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(context).inflate(R.layout.ease_row_chat_history, parent, false);
        return new ViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {

        Conversation conversation;
        if (showFilterData) {
            conversation = filterConversationList.get(position);
        } else {
            conversation = conversationList.get(position);
        }
        setupBackground(holder, conversation);
        showUserInfo(holder, conversation);

        holder.motioned.setVisibility(View.GONE);

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                conversation.openConversation(context);
                setupBadge(holder, conversation);
            }
        });
        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (listener != null) {
                    listener.onLongClick(v, conversation);
                    return true;
                }
                return false;
            }
        });


        showMessage(holder, conversation);

    }

    private void setupBackground(ViewHolder holder, Conversation conversation) {
        if (conversation.isTop()) {
            holder.itemView.setBackgroundColor(context.getResources().getColor(R.color.gray_background_0));
        } else {
            holder.itemView.setBackgroundResource(0);
        }
    }

    private void showMessage(ViewHolder holder, Conversation conversation) {
        setupBadge(holder, conversation);

        Message lastMessage = conversation.getLastMessage();

        if (lastMessage == null) {
            Log.e(TAG, "onBindViewHolder:lastMessage为空 ");
            return;
        }

        // holder.tv_message.setText(EmojiManager.getSmiledText(context, ChatMessageUtil.getMessageDigest(lastMessage, context)), TextView.BufferType.SPANNABLE);
        MoonUtils.identifyFaceExpression(context, holder.tv_message, conversation.getContent(), ImageSpan.ALIGN_BOTTOM, 0.6f);
        holder.time.setText(DateUtils.getTimestampString(lastMessage.getCreated()));
        //发送失败，展示红点，用以提示
        if (Utils.isSendMessage(lastMessage) && lastMessage.getSendState() != null && lastMessage.getSendState() == Constant.IM_SEND_STATE_FAIL) {
            holder.msgState.setVisibility(View.VISIBLE);
        } else {
            holder.msgState.setVisibility(View.GONE);
        }
    }

    private void setupBadge(ViewHolder holder, Conversation conversation) {
        if (conversation.getUnReadCount() > 0) {
            holder.tv_unreadCount.setText(String.valueOf(conversation.getUnReadCount()));
            holder.tv_unreadCount.show();
        } else {
            holder.tv_unreadCount.hide();
        }
    }

    private void showUserInfo(ViewHolder holder, Conversation conversation) {
        final int type = conversation.getType();
        if (type == Constant.CONVERSATION_TYPE_C2C) {
            holder.iv_officialLogo.setVisibility(View.GONE);
            //Glide.with(context).load(conversation.getIcon()).diskCacheStrategy(DiskCacheStrategy.ALL).error(R.drawable.tx_default_avatar_1).into(holder.iv_avatar);
            GlideLoadUtils.glideLoad(context, conversation.getIcon(), holder.iv_avatar, R.drawable.tx_default_avatar_1);

        } else {
            holder.iv_officialLogo.setVisibility(View.VISIBLE);
            holder.iv_avatar.setImageResource(conversation.getIconResourceId());
        }
        holder.tv_name.setText(conversation.getTitle());
    }


    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position, @NonNull List<Object> payloads) {
        if (payloads.isEmpty()) {
            onBindViewHolder(holder, position);
        } else {
            Conversation conversation;
            if (showFilterData) {
                conversation = filterConversationList.get(position);
            } else {
                conversation = conversationList.get(position);
            }
            for (Object payload : payloads) {
                Integer refreshFlag;
                if (payload instanceof Integer) {
                    refreshFlag = (Integer) payload;
                } else {
                    break;
                }
                switch (refreshFlag) {
                    case REFRESH_MESSAGE:
                        showMessage(holder, conversation);
                        break;

                    case REFRESH_USER_INFO:
                        showUserInfo(holder, conversation);
                        break;
                    case REFRESH_BACKGROUND:
                        setupBackground(holder, conversation);
                }
            }
        }
    }

    @Override
    public int getItemCount() {
        if (showFilterData) {
            return filterConversationList.size();
        }
        return conversationList.size();
    }


    private void getUserInfo(final ViewHolder holder, final String userId) {
        if (!Helper.getInstance().isNetworkConnected()) {
            ((BaseActivity) context).showToast_v1(context.getString(R.string.network_anomalies));
            return;
        }
        RetrofitManager.getInstance().createRequest(UserService.class)
                .getUserInfo(userId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        idList.remove(userId);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse:从服务端获取联系人信息出错 " + response.message());
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "onResponse:从服务端获取联系人信息出错 " + result.getMsg());

                            return;
                        }

                        JSONObject object = (JSONObject) result.getData();

                        User user = object.toJavaObject(User.class);
                        user.setUId(userId);
                        user.setType(Constant.USER_TYPE_TEMP);
                        DBManager.getInstance().getDaoSession().getUserDao().insertOrReplace(user);//作为临时联系人，保存在用户表中

                       // Glide.with(context).load(user.getAvatar()).diskCacheStrategy(DiskCacheStrategy.ALL).error(R.drawable.tx_default_avatar).into(holder.iv_avatar);
                        GlideLoadUtils.glideLoad(context, user.getAvatar(), holder.iv_avatar, R.drawable.tx_default_avatar_1);

                        holder.tv_name.setText(user.getUsername());

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        idList.remove(userId);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }

    /**
     * 当展示过滤数据点额时候，通知item 移除
     *
     * @param conversation
     */
    public void notifyItemRemovedOnShowFilterData(Conversation conversation) {
        int index = filterConversationList.indexOf(conversation);
        notifyItemRemoved(index);
    }

    /**
     * 当展示过滤数据的时候，通知item 刷新
     *
     * @param conversation
     */
    public void notifyItemChangedOnShowFilterData(Conversation conversation, int refreshFlags) {
        int index = filterConversationList.indexOf(conversation);
        notifyItemChanged(index, refreshFlags);
    }


    public class ViewHolder extends RecyclerView.ViewHolder {

        ImageView iv_avatar;
        TextView tv_name;
        TextView tv_message;
        TextView time;
        BottomBarBadge tv_unreadCount;
        View msgState;
        TextView motioned;
        ImageView iv_officialLogo;

        public ViewHolder(View itemView) {
            super(itemView);
            iv_avatar = itemView.findViewById(R.id.avatar);
            tv_name = itemView.findViewById(R.id.name);
            tv_unreadCount = itemView.findViewById(R.id.unread_msg_number);
            tv_message = itemView.findViewById(R.id.tv_message);
            time = itemView.findViewById(R.id.time);
            msgState = itemView.findViewById(R.id.msg_state);
            motioned = itemView.findViewById(R.id.mentioned);
            iv_officialLogo = itemView.findViewById(R.id.iv_official_logo);
        }

    }

    public void filter() {
        filter(filterKeyWord);
    }

    public void filter(CharSequence filterKeyWord) {
        this.filterKeyWord = filterKeyWord;
        if (conversationFilter == null) {
            conversationFilter = new ConversationFilter(conversationList);
        }
        conversationFilter.filter(filterKeyWord);
    }


    public void clearFilter() {
        showFilterData = false;
        notifyDataSetChanged();
    }

    public boolean isShowFilterData() {
        return showFilterData;
    }

    public interface InteractionListener {
        void onLongClick(View view, Conversation conversation);
    }

    private class ConversationFilter extends Filter {
        List<Conversation> mOriginalValues = null;

        public ConversationFilter(List<Conversation> mList) {
            mOriginalValues = mList;
        }

        @Override
        protected FilterResults performFiltering(CharSequence prefix) {
            FilterResults results = new FilterResults();

            if (mOriginalValues == null) {
                mOriginalValues = new ArrayList<Conversation>();
            }
            String prefixString = prefix.toString();
            final int count = mOriginalValues.size();
            final ArrayList<Conversation> newValues = new ArrayList<>();

            for (int i = 0; i < count; i++) {
                final Conversation conversation = mOriginalValues.get(i);
                User user = conversation.getToUser();

                if (user == null) {
                    continue;
                }
                String username = user.getUsername();
                if (TextUtils.isEmpty(username)) {
                    continue;
                }
                if (username.startsWith(prefixString)) {
                    newValues.add(conversation);
                } else {
                    final String[] words = username.split(" ");
                    final int wordCount = words.length;

                    for (int k = 0; k < wordCount; k++) {
                        if (words[k].startsWith(prefixString)) {
                            newValues.add(conversation);
                            break;
                        }
                    }
                }
            }

            results.values = newValues;
            results.count = newValues.size();

            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            filterConversationList.clear();
            if (results.values != null) {
                showFilterData = true;
                filterConversationList.addAll((List<Conversation>) results.values);
                notifyDataSetChanged();
            }
        }
    }
}
